package com.esreport.Utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esreport.okhttp.OkHttpUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xuweiwei
 * @date 2019/7/5
 */
@Slf4j
public class ArticleUtil {

    private static OkHttpClient httpClient = OkHttpUtils.buildHttpClient();
    public static SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static Map<String, Object> filter(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Object> entry = iter.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value == null) {
                result.put(key, "");
            } else {
                if(value instanceof Date){
                    Date date = (Date) value;
                    result.put(key,sdf.format(date));
                }else {
                    result.put(key, value.toString());
                }
            }
        }
        return result;
    }

    public static Map<String, Object> parse(Integer siteId, String prefix, Map<String, Object> sourceMap, Map<Integer, Integer> commentMap) {
        Integer id = ((Long) sourceMap.get("ID")).intValue();
        Map<String, Object> map = filter(sourceMap);
        String logo = (String) map.get("Logo");
        String PluralPicsFlag = (String) map.get("PluralPicsFlag");
        String Attribute = (String) map.remove("Attribute");
        String GoodViewCount = (String) map.get("GoodViewCount");
        String Type = (String) map.get("Type");
        String Content = (String) map.remove("Content");
        //拼接logo地址
        String newLogo = UrlUtil.join(prefix, logo);
        map.put("Logo", newLogo);
        Integer count = commentMap.get(id);
        if (count == null || count < 0) {
            count = 0;
        }
        map.put("counts", count);
        if (StringUtils.isEmpty(PluralPicsFlag)) {
            map.put("PluralPicsFlag", "0");
        }


        if (StringUtil.isNotEmpty(Attribute)) {
            // 音频、电台
            if (Attribute.indexOf("audio") != -1) {
                map.put("livetype", "audio");
            }
            if (Attribute.indexOf("media") != -1) {
                map.put("livetype", "media");
            }
            if (Attribute.indexOf("camera") != -1) {
                map.put("livetype", "camera");
                map.put("link", "");
            }
        }

        if (StringUtil.isEmpty(GoodViewCount)) {
            map.put("GoodViewCount", "0");
        }

        //普通新闻+多图样式
        if ("1".equals(Type) && "1".equals(PluralPicsFlag)) {
            JSONObject json = new JSONObject();
            Document doc = Jsoup.parse(Content);
            org.jsoup.nodes.Element body = doc.body();
            Elements imgs = body.select("img");
            List<String> list = new ArrayList<>();//第一次过滤掉gif后剩下的src集合
            List<String> list1 = new ArrayList<>();//第二次过滤掉不符合尺寸的图片后剩下的src集合
            for (org.jsoup.nodes.Element e : imgs) {
                String esrc = e.attr("src");
                String[] array = esrc.split("\\.");
                if (array[array.length - 1].equalsIgnoreCase("jpg") || array[array.length - 1].equalsIgnoreCase("png") || array[array.length - 1].equalsIgnoreCase("jpeg")) {
                    list.add(e.attr("src"));
                }
            }
            if (siteId == 204) {//黄浦不过滤尺寸
                if (list.size() >= 3) {
                    int num = 0;
                    for (String imgUrl : list) {
                        json.put("img" + num, imgUrl);
                        num++;
                    }
                    map.put("Content", json);
                } else {
                    map.put("PluralPicsFlag", "0");
                    map.put("Content", "");
                }
            } else {
                if (list.size() >= 3) {//过滤掉gif格式的图片  如果图片小于三张  则使用普通样式
                    for (String src : list) {
                        try {
                            if (src.contains("vod")) {//如果是七牛上传的图片 获取宽和高
                                String result = OkHttpUtils.httpGet(httpClient, src + "?imageInfo");
                                JSONObject imageInfo = JSON.parseObject(result);
                                if (imageInfo.getInteger("width") >= 600 && imageInfo.getInteger("height") >= 400) {
                                    list1.add(src);
                                }
                            }
                        } catch (Exception e2) {
                            log.error("解析图片宽高异常", e2);
                            map.put("PluralPicsFlag", "0");
                            map.put("Content", "");
                        }
                    }
//					经过尺寸过滤后的图片如果大于三张
                    if (list1.size() >= 3) {
                        int num = 0;
                        for (String imgUrl : list1) {
                            json.put("img" + num, imgUrl);
                            num++;
                        }
                        map.put("Content", json);
                    } else {
                        map.put("PluralPicsFlag", "0");
                        map.put("Content", "");
                    }
                } else {
                    map.put("PluralPicsFlag", "0");
                    map.put("Content", "");
                }
            }
        } else if ("2".equals(Type)) {
            //获取content中img的src（图片地址）
            JSONObject imgJSON = new JSONObject();
            Document document = Jsoup.parse(Content);
            Elements elements = document.select("img");
            int index = 0;
            for (Element element : elements) {
                String imgSrc = element.attr("src");
                imgJSON.put("img" + index, imgSrc);
                index++;
            }
            map.put("Content", imgJSON);
        }
        return map;
    }
}
